<template>
  <view class="search">
    <view class="search_row">
      <input v-model="searchValue" placeholder="请输入您要搜索的商品" />
      <button @click="handleCancel" :hidden="!isFocus">取消</button>
    </view>
    <view class="search_content">
      <navigator
        :url="'/pages/goods_detail/goods_detail?goods_id=' + item.goods_id"
        class="search_item" v-for="item in goods" :key="item.goods_id"
        v-html="item.goods_name">
        <!-- {{ item.goods_name }} -->
      </navigator>
    </view>
  </view>
</template>

<script>
  import {
    debounce
  } from "../../utils/util"
  export default {
    data() {
      return {
        goods: [],
        // 取消 按钮 是否显示
        isFocus: false,
        // 输入框的值
        searchValue: "",
      }
    },
    TimeId: -1,
    watch: {
      searchValue: function(newVal, oldVal) {
        if (newVal.trim() && newVal !== oldVal) {
          this.isFocus = true
          debounce(this.search)()
        } else if (newVal.trim().length === 0) {
          this.goods = []
        }
      },
    },
    methods: {
      handleCancel() {
        this.searchValue = ""
        this.isFocus = false
        this.goods = []
      },
      search() {
        this.$http({
          url: "/goods/qsearch",
          method: "GET",
          data: {
            query: this.searchValue,
          },
        }).then((res) => {
          // 匹配关键字正则
          const replaceReg = new RegExp(this.searchValue, "g")
          // 高亮替换v-html值
          const replaceString =
            '<span style="color: red;">' + this.searchValue + "</span>"
          const resHtml = res.map((v) => {
            // 开始替换
            v.goods_name = v.goods_name.replace(replaceReg,
              replaceString)
            return v
          })
          this.goods = resHtml
        })
      },
    },
    onload() {},
  }
</script>

<style lang="scss">
  .search {
    .search_row {
      height: 88upx;
      padding: 10upx;
      display: flex;
      position: fixed;
      width: 100%;
      left: 0;
      top: 0;
      /* #ifdef H5 */
      top: 88upx;
      /* #endif */
      z-index: 99;
      background: #fff;

      input {
        flex: 1;
        height: 100%;
        padding-left: 30upx;
        border: 1upx solid #eee;
      }

      button {
        width: 110upx;
        height: 100%;
        padding: 0;
        margin: 0 10upx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 26upx;
      }
    }

    .search_content {
      margin-top: 88upx;

      .search_item {
        background-color: #fff;
        font-size: 26upx;
        padding: 15upx 10upx;
        border-bottom: 1upx solid #ccc;

        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
</style>
